//
//  HzlTool.m
//  ThatCarDemo
//
//  Created by SDMac on 15/7/16.
//  Copyright (c) 2015年 SDMac. All rights reserved.
//

#import "HzlTool.h"
#import <CommonCrypto/CommonDigest.h>

@implementation HzlTool

+ (NSString *)nowTimeWithFormatter:(NSString*)formatter
{
    // 获取系统的当前时间
    NSDate *date = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:formatter];
    return [dateformatter stringFromDate:date];
}

// 根据日期格式返回字符串
+ (NSString*)timeStringWithDate:(NSDate *)date formatter:(NSString*)formatter
{
    // 设置时间显示的格式
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:formatter];
    
    return [dateformatter stringFromDate:date];
}

// 把字符串转化为NSDate
+ (NSDate*)dateFromString:(NSString *)dateStr formatter:(NSString*)formatter
{
    // NSString *dateStr=@"2013-08-13 20:28:40";
    // 将传入时间转化成需要的格式 yyyy-MM-dd HH:mm:ss
    
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:formatter];
    
    NSDate *fromdate=[format dateFromString:dateStr];
    NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
    
    NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
    NSDate *fromDate = [fromdate  dateByAddingTimeInterval: frominterval];
    
    // NSLog(@"fromdate=%@",fromDate);
    
    //    NSInteger iSeconds = lTime % 60;
    //    NSInteger iMinutes = (lTime / 60) % 60;
    //    NSInteger iHours = (lTime / 3600);
    //    NSInteger iDays = lTime/60/60/24;
    //    NSInteger iMonth = lTime/60/60/24/12;
    //    NSInteger iYears = lTime/60/60/24/384;
    
    return fromDate;
}

/** 对比两个时间相差多久 */
+ (long)timeInterval:(NSDate *)toDate fromDate:(NSDate *)fromDate
{
    // 得出传入的NSDate和当前NSDate相差多少秒
    double intervalTime = [fromDate timeIntervalSinceReferenceDate] - [toDate timeIntervalSinceReferenceDate];
    
    long lTime = (long)intervalTime;
    
    return lTime;
}

/** 对比传入的NSDate与当前的时间相差多少天 */
+ (long)timeIntervalWithString:(NSString *)toDateString fromDateString:(NSString *)fromDateString
{
    NSDate *toDate = [HzlTool dateFromString:toDateString formatter:@"yyyyMMdd"];
    NSDate *fromDate = [HzlTool dateFromString:fromDateString formatter:@"yyyyMMdd"];
    long timeInterval = [HzlTool timeInterval:toDate fromDate:fromDate];
    
    return timeInterval/60/60/24;
}

/** 对比传入的NSDate与当前的时间相差多少秒 */
+ (long)dateTimeInterval:(NSDate *)fromDate
{
    // 获取当前时间
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    
    double intervalTime = [fromDate timeIntervalSinceDate:localeDate];
    
    // 得出传入的NSDate和当前NSDate相差多少秒
    //double intervalTime = [fromDate timeIntervalSinceReferenceDate] - [localeDate timeIntervalSinceReferenceDate];
    
    long lTime = (long)intervalTime;
    
    return lTime;
}

/** 根据传入的NSDate获得星期，年，月，日，时，分 */
+ (NSInteger)componentsWithDate:(NSDate*)nowDate
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitWeekday | NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear;
    
    NSDateComponents *nowCmps = [calendar components:unit fromDate:nowDate];
    
    return nowCmps.year;
}

/** 返回于现在时间相差多久的时间 */
+ (NSString*)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs formatter:(NSString*)formatter
{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:secs];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:formatter];
    return [dateformatter stringFromDate:date];
}

/** 对字符串进行MD5加密 */
+ (NSString *)md5:(NSString *)string
{
    if (string != nil && string.length > 0)
    {
        const char *original_str = [string UTF8String];
        
        unsigned char result[CC_MD5_DIGEST_LENGTH];
        
        CC_MD5(original_str,(CC_LONG)strlen(original_str),result);
        
        NSMutableString *hash = [NSMutableString string];
        
        for (NSUInteger i = 0; i < 16; i++)
        {
            [hash appendFormat:@"%02X", result[i]];
        }
        
        return [hash lowercaseString];
    }
    
    return nil;
}

/** 字典转json字符串 */
+ (NSString *)JsonStringWithDictionary:(NSDictionary*)dic
{
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil] ;
    
    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return jsonStr;
}

/** 调用电话phone */
+ (void)callPhoneWithString:(NSString*)string
{
    NSString *urlString = [NSString stringWithFormat:@"tel://%@",string];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
}

/** 手机合法验证 */
+ (BOOL)isValidateMobile:(NSString *)mobile
{
    if (mobile == nil || mobile.length == 0)
    {
        return NO;
    }
    
    //手机号以13， 15，18开头，八个 \d 数字字符
    //NSString *phoneRegex = @"^((13[0-9])|(14[57])|(15[^4\\D])|(17[0678])|(18[0-9]))\\d{8}$";
    NSString *phoneRegex = @"^1\\d{10}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

/** 判断字符串是否为空 */
+ (BOOL)isEmptyString:(NSString *)string
{
    if (string == nil || string == NULL)
    {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    if ([string isEqualToString:@"(null)"])
    {
        return YES;
    }
    if (string.length == 0)
    {
        return YES;
    }
    else
    {
        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
        
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
        
        NSString *trimedString = [string stringByTrimmingCharactersInSet:set];
        
        if (trimedString.length == 0)
        {
            return YES;
        }
    }
    
    return NO;
}

/** 动态 计算行高 根据字符串的实际内容的多少 在固定的宽度和字体的大小，动态的计算出实际的高度 */
+ (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)size
{
    //iOS7之后
    /*
     第一个参数: 预设空间 宽度固定  高度预设 一个最大值
     第二个参数: 行间距 如果超出范围是否截断
     第三个参数: 属性字典 可以设置字体大小
     */
    //xxxxxxxxxxxxxxxxxx
    //ghjdgkfgsfgskdgfjk
    //sdhgfsdjkhgfjd
    
    NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};
    CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
    //返回计算出的行高
    return rect.size.height;
}
/** 获取iOS版本号 */
+ (double)getCurrentIOS
{
    return [[[UIDevice currentDevice] systemVersion] doubleValue];
}

/** 判断是否是第一响应者如果是，取消响应 */
+ (void)isFirstResponder:(UITextField*)textField
{
    if ([textField isFirstResponder])
    {
        [textField resignFirstResponder];
    }
}

/** 匹配字符串 */
+ (BOOL)matching:(NSString *)str
{
    NSString * regex = @"^[@A-Za-z0-9!#$%^&*.~]{6,20}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    return isMatch;
}

/** 剔除用户名中的空格 */
+ (NSString *)pathComponents:(NSString*)pathre
{
    NSMutableString *str=[[NSMutableString alloc] initWithString:pathre];
    NSArray *arr2=[str componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];
    for(NSString *str in arr2){
        if([str isEqualToString:@""]){
            continue;
        }
    }
    NSMutableArray *newArr=[NSMutableArray arrayWithArray:arr2];
    [newArr removeObject:@""];
    NSString *str1=[newArr componentsJoinedByString:@""];
    return str1;
}

/** 判断数字是否大于10 */
+ (NSString*)addZero:(NSString*)string
{
    if ([string integerValue] < 10)
    {
        return [NSString stringWithFormat:@"0%ld",[string integerValue]];
    }
    
    return string;
}

/** 车牌号合法验证 */
+ (BOOL)isValidateCarNo:(NSString *)carNo
{
    NSString *carNumRegex = @"(^[\u4e00-\u9fa5][A-Z]{1}[A-Za-z0-9]{5}$)";
    NSPredicate *carNumPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carNumRegex];
    BOOL predicate = [carNumPredicate evaluateWithObject:carNo];
    return predicate;
}

/** 发动机号合法验证 */
+ (BOOL)isValidateEngineNo:(NSString *)engineNo
{
    if (engineNo.length == 16)
    {
        return YES;
    }
    
    return NO;
}

/** 车架号合法验证 */
+ (BOOL)isValidateClassNo:(NSString *)classNo
{
    if (classNo.length == 17)
    {
        return YES;
    }
    
    return NO;
}

/** 判断身份证号是否正确 (单位组织机构代码) */
+ (BOOL)isValidateIdentifyCard:(NSString *)identifyCard
{
    if (identifyCard == nil || identifyCard.length == 0)
    {
        return NO;
    }
    
    NSString *identfiyCardRegex = @"^(\\d{15}|\\d{18}|\\d{17}[xX]{1})$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",identfiyCardRegex];
    BOOL predicate = [identityCardPredicate evaluateWithObject:identifyCard];
    return predicate;
}

/** 把数据保存到磁盘上 */
+ (void)userDefaultsWithDictionary:(NSDictionary*)dict
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    for (NSInteger i = 0; i < dict.allKeys.count; i++)
    {
        NSString *key = dict.allKeys[i];
        
        [userDefaults setObject:dict[key] forKey:key];
    }
    
    //立即同步到磁盘
    [userDefaults synchronize];
}

#pragma - project Methods

/** 把用户名和密码保存到磁盘上 */
+ (void)saveUserInfo:(NSString*)userName password:(NSString*)password
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@"666" forKey:@"saveUserInfo"];
    
    if (![HzlTool isEmptyString:userName])
    {
        [userDefaults setObject:userName forKey:@"userName"];
    }
    if (![HzlTool isEmptyString:password])
    {
        [userDefaults setObject:password forKey:@"password"];
    }
    
    //立即同步到磁盘
    [userDefaults synchronize];
}

+ (void)deleteUserInfo;
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    [userDefaults setObject:@"" forKey:@"saveUserInfo"];
    [userDefaults setObject:@"" forKey:@"userName"];
    [userDefaults setObject:@"" forKey:@"password"];
    
    //立即同步到磁盘
    [userDefaults synchronize];
}

/** 读取磁盘上的用户名和密码 */
+ (NSDictionary*)userInfo
{
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    
    NSString *saveUserInfo = [userDefaults valueForKey:@"saveUserInfo"];
    NSString *userName = [userDefaults valueForKey:@"userName"];
    NSString *password = [userDefaults valueForKey:@"password"];
    
    NSMutableDictionary *userDict = [NSMutableDictionary dictionaryWithCapacity:0];
    if (![HzlTool isEmptyString:saveUserInfo])
    {
        [userDict setObject:saveUserInfo forKey:@"saveUserInfo"];
    }
    if (![HzlTool isEmptyString:userName])
    {
        [userDict setObject:userName forKey:@"userName"];
    }
    if (![HzlTool isEmptyString:password])
    {
        [userDict setObject:password forKey:@"password"];
    }
    if (userDict.count)
    {
        return userDict;
    }
    
    return nil;
}

+ (BOOL)isMoney:(NSString*)material
{
    if (![HzlTool isEmptyString:material] && [material hasSuffix:@"(金额)"])
    {
        return YES;
    }
    
    return NO;
}

/** 判断token是否过期 */
+ (BOOL)isTokenOverdue:(NSDate *)fromDate
{
    long lTime = [HzlTool dateTimeInterval:fromDate];
    
    if (lTime > 7000)
    {
        return YES;
    }
    
    return NO;
}
+ (BOOL)validationIntegral:(NSString*)integral
{
    if ([HzlTool isEmptyString:integral])
    {
        return YES;
    }
    else if ([integral isEqualToString:@"."])
    {
        return NO;
    }
    else if ([integral hasPrefix:@"."] || [integral hasSuffix:@"."])
    {
        return NO;
    }
    
    return YES;
}

+ (double)roundFloat:(double)integral
{
    //return (floorf(integral*100 + 0.5))/100;
    return integral;
}

+ (NSAttributedString*)attributedString:(NSString*)leftStr center:(NSString*)centerStr
{
    NSString *string = [NSString stringWithFormat:@"%@%@",leftStr, centerStr];
    
    NSRange centerRang = [string rangeOfString:centerStr];
    
    NSMutableAttributedString *attributed = [[NSMutableAttributedString alloc] initWithString:string];
    [attributed addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:centerRang];
    
    return attributed;
}

+ (NSString*)formatterWithString:(NSString*)integralString
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    return [formatter stringFromNumber:[NSNumber numberWithDouble:[integralString doubleValue]]];
}

@end
